﻿using System;
using System.IO;
using System.Text;
using UnityEngine;

public static partial class Utility
{

    /// <summary>
    /// 文件处理工具库
    /// </summary>
    public static class File
    {

        /// <summary>
        /// 检测文件是否存在
        /// </summary>
        /// <param name="path">文件路径</param>
        /// <returns></returns>
        public static bool IsExists(string path)
        {
            FileInfo fileInfo = new FileInfo(path);
            return fileInfo.Exists;
        }

        /// <summary>
        /// 获取文件数据
        /// </summary>
        /// <param name="path">文件路径</param>
        /// <returns></returns>
        public static string ReadFile(string path)
        {
            // 获取标准路径
            path = Path.FormatStandardPath(path);
            // 文件夹的路径
            string dir = path.Substring(0, path.LastIndexOf("/"));
            if (!Directory.Exists(dir))
            {
                Logger.LogFormat("文件目录 {0} 不存在", dir.RichTextErrorColor());
                return string.Empty;
            }
            if (!IsExists(path))
            {
                Logger.LogFormat("目标文件 {0} 不存在", path.RichTextErrorColor());
                return string.Empty;
            }

            try
            {
                using (FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read))
                {
                    fileStream.Seek(0, SeekOrigin.Begin);
                    var bytes = new byte[fileStream.Length];
                    fileStream.Read(bytes, 0, (int)fileStream.Length);
                    string content = Encoding.UTF8.GetString(bytes);
                    fileStream.Flush();
                    fileStream.Dispose();
                    fileStream.Close();
                    return content;
                }
            }
            catch (Exception e)
            {
                Logger.Log(e.Message.RichTextErrorColor());
                Logger.Log("文件读取异常：" + path.RichTextErrorColor());
                return string.Empty;
            }
        }

        /// <summary>
        /// 写入文件数据
        /// </summary>
        /// <param name="path">文件路径</param>
        /// <param name="content">文件内容</param>
        public static void WriteFile(string path, string content)
            => WriteFile(path, Encoding.Unicode.GetBytes(content));

        /// <summary>
        /// 写入文件数据
        /// </summary>
        /// <param name="path">文件路径</param>
        /// <param name="data">文件数据</param>
        public static void WriteFile(string path, byte[] data)
        {
            // 获取标准路径
            path = Path.FormatStandardPath(path);
            // 文件夹的路径
            int lastIdx = path.LastIndexOf("/");
            if (lastIdx >= 0)
            {
                string dir = path.Substring(0, lastIdx);
                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }
            }
            FileInfo file = new FileInfo(path);
            if (file.Exists)
            {
                file.Delete();
            }
            try
            {
                using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write))
                {
                    fs.Write(data, 0, data.Length);
                    fs.Close();
                }
            }
            catch (IOException ex)
            {
                throw new Exception(ex.Message);
            }
        }

        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="path">文件路径</param>
        /// <returns></returns>
        public static bool DeleteFile(string path)
        {
            // 获取标准路径
            path = Path.FormatStandardPath(path);
            // 文件夹的路径
            string dir = path.Substring(0, path.LastIndexOf("/"));
            if (!Directory.Exists(dir))
            {
                Logger.LogFormat("文件目录 {0} 不存在", dir.RichTextErrorColor());
                return false;
            }
            if (!IsExists(path))
            {
                Logger.LogFormat("目标文件 {0} 不存在", path.RichTextErrorColor());
                return false;
            }

            Directory.Delete(path);
            Logger.Log("文件删除成功：" + path.RichTextErrorColor());
            return true;
        }

        /// <summary>
        /// 获取文件的 MD5 值
        /// </summary>
        /// <param name="filePath">文件的绝对路径</param>
        /// <returns></returns>
        public static string GetMD5HashFromFile(string filePath)
        {
            try
            {
                using (FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                {
                    System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
                    byte[] retVal = md5.ComputeHash(file);
                    file.Flush();
                    file.Close();

                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < retVal.Length; i++)
                    {
                        sb.Append(retVal[i].ToString("x2"));
                    }
                    return sb.ToString();
                }
            }
            catch (Exception ex)
            {
                throw new Exception("GetMD5HashFromFile() fail, error:" + ex.Message);
            }
        }

        /// <summary>
        /// 获取文件大小
        /// </summary>
        /// <param name="filePath">文件的绝对路径</param>
        /// <returns></returns>
        public static string GetFileSize(string filePath)
        {
            FileInfo fileInfo;
            long len = 0;
            try
            {
                fileInfo = new FileInfo(filePath);
                if (fileInfo.Exists)
                    len = fileInfo.Length;
            }
            catch (Exception e)
            {
                Debug.Log(e);
            }
            return GetFileSize(len);
        }

        public static string GetFileSize(long filesize)
        {
            return GetSize(filesize);
        }

        public static string GetSize(long filesize)
        {
            if (filesize < 0)
            {
                return "-" + GetSize(-filesize);
            }
            else if (filesize >= 1024 * 1024 * 1024)
            {
                return string.Format("{0:0.00} GB", (double)filesize / (1024 * 1024 * 1024));
            }
            else if (filesize >= 1024 * 1024)
            {
                return string.Format("{0:0.00} MB", (double)filesize / (1024 * 1024));
            }
            else if (filesize >= 1024)
            {
                return string.Format("{0:0.00} KB", (double)filesize / 1024);
            }
            else
            {
                return string.Format("{0:0.00} bytes", filesize);
            }
        }
    }
}
